var Kuo_login = {
    $Securitytime:60,//缓存时间
    $Securitynum:3,//最多错误次数
    $DATA:{
        code:0,
        data:null,
        msg:"",
        token:""
    },DelCode: async ($name)=>{
        return await Mem.Del("facode/"+$name);
    },GetCode: async ($name)=>{
        return await Mem.Get("facode/"+$name);
    },StmpMail: async ($name,$neirong,$CANSHU)=>{
        let $features = await Kuoplus("login");
        const Stmp = $features['configure']['Stmp'];
        const net = require('net');
        const assert = require('assert');
        const host = Stmp[0];
        var port = Stmp[1];
        var user = Stmp[2];
        var pass = Stmp[3];
        var to = $name;
        var subject = $features['configure'][$CANSHU['leixing']]?$features['configure'][$CANSHU['leixing']]['3']:'';
        subject += " "+Mode("Tools").Date("Y-m-d H:i:s");
        var msg = $neirong;
        Kuolog('userlog',0,7, $neirong ,"StmpMail","login",$name);
        return new Promise((resolvex,reject) => {
            let client = net.createConnection({host,port},async() => {
                let code
                code = await getData()
                assert(code == 220)
                sendData('HELO ' + host)
                code = await getData()
                assert(code == 250)
                // 要登陆
                sendData('auth login')
                code = await getData()
                assert(code == 334)
                sendData(Buffer.from(user).toString('base64'))
                code = await getData()
                assert(code == 334)
                sendData(Buffer.from(pass).toString('base64'))
                code = await getData()
                assert(code == 235)
                sendData(`MAIL FROM:<${user}>`)
                code = await getData()
                assert(code == 250)
                sendData(`RCPT TO:<${to}>`)
                code = await getData()
                assert(code == 250)
                sendData('DATA')
                code = await getData()
                assert(code == 354)
                sendData(`SUBJECT:${subject}`)
                sendData(`FROM:${user}`)    
                sendData(`TO:${to}\r\n`)
                sendData(`${msg}\r\n.`)
                code = await getData()
                sendData(`QUIT`)
                resolvex(true);
            })
           
            function getData() {
                return new Promise((resolve,reject) => {
                    next()
                    function next(){
                        if(data) {
                            let temp = data
                            data =null
                            resolve(temp)
                        } else {
                            setTimeout(next,0)
                        }
                    }
                })
            }
            
            function sendData(msg) {
                client.write(msg+'\r\n')
            }
            let data = null
            client.on('data', d => {
              
                data = d.toString().substring(0,3)
            })
            client.on('end', () => {
                resolvex(true);
            })
        }).then(async function(data){

            
            return true;
        }).catch(async (e) => {

            return false;
        });
        
    },MailBox: async ($name,$neirong,$CANSHU)=>{
        

        let $features = await Kuoplus("login");

        if($features['configure']['Stmp'] && $features['configure']['Stmp']['0'] != ""){

            return await Kuo_login.StmpMail($name,$neirong,$CANSHU);
        }
      
        let AccountName = $features['configure']['邮件配置']?$features['configure']['邮件配置']['0']:"";
        let FromAlias = $features['configure']['邮件配置']?$features['configure']['邮件配置']['1']:"";
        let accessKeyId = $features['configure']['邮件配置']?$features['configure']['邮件配置']['2']:"";
        let accessKeySecret = $features['configure']['邮件配置']?$features['configure']['邮件配置']['3']:"";
        let Subject = $features['configure'][$CANSHU['leixing']]?$features['configure'][$CANSHU['leixing']]['3']:'';
        let qianming = {
            Action:"SingleSendMail",
            AccountName:AccountName,
            AddressType:1,
            ReplyToAddress:"false",
            Subject:Subject,
            ToAddress:$name,
            FromAlias:FromAlias,
            HtmlBody:$neirong,
            AccessKeyId:accessKeyId,
            SignatureMethod:"HMAC-SHA1",
            SignatureNonce:Mode("Tools").Uuid(),
            SignatureVersion:"1.0",
            Format:"json",
            Version:"2015-11-23",
            Timestamp: ""+new Date().toISOString()
        }
        let sortedQueryString = getarray(azpaixu(qianming),true);
        sortedQueryString = 'GET&' + encodeURIComponent('/') +'&'  + encodeURIComponent(sortedQueryString);
        qianming['Signature'] = ( CRYPTO.createHmac('sha1', accessKeySecret +'&' ).update(Buffer.from(sortedQueryString, 'utf-8')).digest('base64'));
        for(var xx in qianming){
            qianming[xx] = encodeURIComponent(qianming[xx]);
        }
        let fan = await  GET("https://dm.aliyuncs.com/?"+getarray(qianming));
        fan = json_decode(fan);
        fan.neirong = $neirong;
        await Kuolog('userlog',0,7, fan ,"MailBox","login",$name);
        if(fan && fan['EnvId']){
            return true;
        }
        return false;

    },ShouJi: async ($name,$neirong,$CANSHU)=>{
        let $features = await Kuoplus("login");
        let SignName = $features['configure']['短信配置']?$features['configure']['短信配置']['0']:"";
        let TemplateCode = $features['configure'][$CANSHU['leixing']]?$features['configure'][$CANSHU['leixing']]['1']:'';
        let duiying = $features['configure'][$CANSHU['leixing']]?$features['configure'][$CANSHU['leixing']]['2']:'{}';
        let accessKeyId = $features['configure']['短信配置']?$features['configure']['短信配置']['1']:"";
        let accessKeySecret = $features['configure']['短信配置']?$features['configure']['短信配置']['2']:"";
        let TemplateParam = {};
        duiying = json_decode(duiying);
        for(var ii in duiying){
            TemplateParam[ii] = $CANSHU[duiying[ii]];
        }
        let qianming = {
            Action:"SendSms",
            PhoneNumbers:$name,
            SignName:SignName,
            TemplateCode:TemplateCode,
            TemplateParam:JSON.stringify(TemplateParam),
            AccessKeyId:accessKeyId,
            SignatureMethod:"HMAC-SHA1",
            SignatureNonce:Mode("Tools").Uuid(),
            SignatureVersion:"1.0",
            Format:"json",
            Version:"2017-05-25",
            Timestamp: ""+new Date().toISOString()
        };
        let sortedQueryString = getarray(azpaixu(qianming),true);
        sortedQueryString = 'GET&' + encodeURIComponent('/') +'&'  + encodeURIComponent(sortedQueryString);
        qianming['Signature'] = ( CRYPTO.createHmac('sha1', accessKeySecret +'&' ).update(Buffer.from(sortedQueryString, 'utf-8')).digest('base64'));
        for(var xx in qianming){
            qianming[xx] = encodeURIComponent(qianming[xx]);
        }
        let fan = await  GET("https://dysmsapi.aliyuncs.com/?"+getarray(qianming));
        fan = json_decode(fan);
        fan.neirong = $neirong;
        await Kuolog('userlog',0,6, fan ,"ShouJi","login",$name);
        if(fan && fan['Code'] == "OK"){
            return true;
        }
        return false;
    },SetCode: async ($name,$NUM)=>{
        if(!$NUM){
            $NUM = 60000;
        }
        return await Mem.Set("facode/"+$name,$NUM,120);
    },Fasong: async ($CANSHU)=>{
        let $THIS = Kuo_login;
        let $num = SJ(100000,999999);
        let $features = await Kuoplus("login");
        $CANSHU["CODE"] = $num;
        let $neirong =  $features['configure'][$CANSHU['leixing']]['0'];
       
        for(var $k in $CANSHU ){
            let $v =$CANSHU[$k];
            $neirong = str_replace($k,$v,$neirong);
        }
       
        let $fan = true;
        if($CANSHU['type'] == 1){
            $fan = await $THIS.MailBox($CANSHU['zhanghao'],$neirong,$CANSHU);
        }else{
            $fan = await $THIS.ShouJi($CANSHU['zhanghao'],$neirong,$CANSHU);
        }
        
        if($fan){
            await $THIS.SetCode($CANSHU['zhanghao'],$num);
            return true;
        }else{
            return false;
        }

    },REG: async ($CANSHU)=>{
        let $features = await Kuoplus("login");
        let $files = "";
        let $isdownffile = false;
        if( isset($CANSHU['tou']) ){
            if( strpos( $CANSHU['tou'],"://")!== false){
                $files  = '/attachment/touxiang/'+Mode("Tools").Date("Y-m")+'/'+Md5($CANSHU['tou'])+'.png';
                $isdownffile = true;
            }
        }
        let $shuju = {
            'nickname':isset($CANSHU['name']) ? Mode("Tools").Xss( $CANSHU['name'] ) : Mode("Tools").Uuid(),
            'sex': $CANSHU['sex']?$CANSHU['sex']: -1,
            'avatar':$files,
            'regip':$CANSHU['ip']?$CANSHU['ip']:'0',
            'regtime':Mode("Tools").Time(),
            'accountoff':1,
        };
        $shuju['security'] = Md5(implode('_$_',$shuju ));
        let $tuid =  Mode("Tools").Int($CANSHU['tuid']?$CANSHU['tuid']:0);
        if($tuid > 0){
            let $USER =  await Uid($tuid);
            if( $USER ){
                for(let $i =0; $i < SuperiorNum ; $i++){
                    if($i == 0){
                        $shuju['superior'+$i] = $tuid;
                    }else{
                        $shuju['superior'+$i] = $USER['superior'+($i-1)];
                    }
                }
            }
        }
        let $DB  = await db("user");
        let $uid = await $DB.Insert($shuju);
        if($uid){
            if($isdownffile){
                let filepath = temp+Mode("Tools").Uuid()+'.png';
                try {
                    REQ.get($CANSHU['tou']).pipe(FS.createWriteStream(filepath)).on('close',async function(){
                        let filesx =[{
                            field: "image",
                            name: $CANSHU['tou'],
                            tmp_name: filepath,
                            size: 10000,
                        }];
                        Upload("image",filesx,$files);
                    });
                } catch (error) {}
            }
            if($features['configure']['有效ip数'] && $features['configure']['有效ip数']['0']){
                let $cishu = await Mem.Add(Mode("Tools").Date("Y-m-d")+"/ipyan/"+Md5($shuju['regip']),1);
                if($cishu < $features['configure']['有效ip数']['0'] ){
                    jiaqian( $uid , 0 , 
                    $features['configure']['金额赠送']['0']?$features['configure']['金额赠送']['0']:0 ,
                    $features['configure']['积分赠送']['0']?$features['configure']['积分赠送']['0']:0 ,
                    $features['configure']['货币赠送']['0']?$features['configure']['货币赠送']['0']:0, "reg" , $shuju['regip'] , "login");
                    for(let $i =0; $i < SuperiorNum ; $i++){
                        if(isset($shuju['superior'+$i])){
                            if($shuju['superior'+$i] > 0){
                                jiaqian( $shuju['superior'+$i] , 1 , 
                                $features['configure']['金额赠送'][($i+1)]?$features['configure']['金额赠送'][($i+1)]:0 ,
                                $features['configure']['积分赠送'][($i+1)]?$features['configure']['积分赠送'][($i+1)]:0 ,
                                $features['configure']['货币赠送'][($i+1)]?$features['configure']['货币赠送'][($i+1)]:0,'reg_'+$uid, $shuju['regip'] , "login");
                            }
                        }
                    }
                }
            }
            return $uid;
        }
        return false;
    },Ismail:(yxx)=>{
        if(!yxx || yxx == "" || yxx.length < 4){
            return false;
        }
        var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); 
        if(!reg.test(yxx)){
            return false;
        }else{
            return true;
        }
    },Isphone:(yxx)=>{
        if(!yxx || yxx == "" || yxx.length < 10 || yxx.length > 12){
            return false;
        }
        var reg = new RegExp(/^1\d{10}$/); 
        if(!reg.test(yxx)){
          　return false;
        }else{
            return true;
        }
    },quite:async function(kuo,Context,context){
        let $DATA = Object.assign({},this.$DATA);
        $DATA.code = 1;
        await Mem.Del("session/"+kuo.sessionid);
        Context.body = json_encode($DATA);
    },code:async function(kuo,Context,context){
        Context.headers["content-type"] = "image/svg+xml";
        Context.body = await VCODE(kuo.sessionid);
    }
}